# -*- coding:utf-8 -*-
import uuid

from captcha.conf.settings import settings
import logging

from django.http import FileResponse

logger = logging.getLogger("django")


# 上传图片文件
def fileSave(request, fileFolder):
    import os
    obj = request.FILES.get('file', None)
    logger.info(request.FILES)

    if not os.path.exists(os.path.join(settings.BASE_DIR, "static", fileFolder)):
        os.makedirs(os.path.join(settings.BASE_DIR, "static", fileFolder))

    # obj.name 原始文件名
    fileName = str(uuid.uuid4())
    fileName = fileName.replace("-", "a") + ".jpg"
    path = "static" + "/" + fileFolder + "/" + fileName
    filePath = os.path.join(settings.BASE_DIR, "static", fileFolder, fileName)
    with open(filePath, 'wb') as f:
        for chunk in obj.chunks():
            f.write(chunk)
    return path


# 下载文件
def fileDownload(path):
    file = open(path, 'rb')
    response = FileResponse(file)
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename="PayTemplate.jpg"'
    # PayTemplate.jpg 返回文件的名称
    return response


# 上传任意文件
def postFileSave(request, fileFolder):
    """

    :param request:
    :param fileFolder: 文件夹名
    :return:
    """
    import os
    obj = request.FILES.get('file', None)
    logger.info(request.FILES)

    if not os.path.exists(os.path.join(settings.BASE_DIR, "static", fileFolder)):
        os.makedirs(os.path.join(settings.BASE_DIR, "static", fileFolder))

    path = "static" + "/" + fileFolder + "/" + obj.name

    filePath = os.path.join(settings.BASE_DIR, 'static', fileFolder, obj.name)
    with open(filePath, 'wb') as f:
        for chunk in obj.chunks():
            f.write(chunk)

    return path
